<template>
  <div class="inventory-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>库存管理</h1>
        <p>管理台球厅设备和用品库存</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="addItem">
          <el-icon><Plus /></el-icon>
          添加物品
        </el-button>
        <el-button @click="refreshInventory">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-row">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Box /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ inventoryStats.total }}</div>
            <div class="stat-label">总物品数</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon normal">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ inventoryStats.normal }}</div>
            <div class="stat-label">库存正常</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon low">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ inventoryStats.low }}</div>
            <div class="stat-label">库存不足</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon out">
            <el-icon><Close /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ inventoryStats.out }}</div>
            <div class="stat-label">缺货</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="物品类别">
          <el-select v-model="filterForm.category" placeholder="选择类别" clearable>
            <el-option label="全部" value="" />
            <el-option label="台球用品" value="台球用品" />
            <el-option label="清洁用品" value="清洁用品" />
            <el-option label="维护用品" value="维护用品" />
          </el-select>
        </el-form-item>

        <el-form-item label="库存状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="库存正常" value="normal" />
            <el-option label="库存不足" value="low_stock" />
            <el-option label="缺货" value="out_of_stock" />
          </el-select>
        </el-form-item>

        <el-form-item label="物品名称">
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索物品名称"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="searchItems">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 库存列表 -->
    <el-card class="table-card">
      <el-table :data="filteredItems" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="物品名称" width="150" />
        <el-table-column prop="category" label="类别" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryTagType(scope.row.category)">
              {{ getCategoryText(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentStock" label="当前库存" width="100">
          <template #default="scope">
            <span :class="getStockClass(scope.row)">{{ scope.row.currentStock }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="minStock" label="最低库存" width="100" />
        <el-table-column prop="maxStock" label="最高库存" width="100" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="price" label="单价" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastUpdate" label="最后更新" width="150">
          <template #default="scope">
            {{ formatTime(scope.row.lastUpdate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <div class="inventory-action-buttons">
              <el-button type="primary" size="small" @click="editItem(scope.row)">
                编辑
              </el-button>
              <el-button type="success" size="small" @click="stockIn(scope.row)">
                入库
              </el-button>
              <el-button type="warning" size="small" @click="stockOut(scope.row)">
                出库
              </el-button>
              <el-button type="danger" size="small" @click="deleteItem(scope.row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑物品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑物品' : '添加物品'"
      width="600px"
    >
      <el-form :model="itemForm" :rules="itemRules" ref="itemFormRef" label-width="100px">
        <el-form-item label="物品名称" prop="name">
          <el-input v-model="itemForm.name" placeholder="请输入物品名称" />
        </el-form-item>
        <el-form-item label="SKU编码" prop="sku">
          <el-input v-model="itemForm.sku" placeholder="请输入SKU编码" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="itemForm.category" placeholder="请选择类别">
            <el-option label="台球用品" value="台球用品" />
            <el-option label="清洁用品" value="清洁用品" />
            <el-option label="维护用品" value="维护用品" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前库存" prop="currentStock">
          <el-input-number v-model="itemForm.currentStock" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="最低库存" prop="minStock">
          <el-input-number v-model="itemForm.minStock" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="最高库存" prop="maxStock">
          <el-input-number v-model="itemForm.maxStock" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="itemForm.unit" placeholder="如：个、支、套" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input-number v-model="itemForm.price" :min="0" :precision="2" controls-position="right" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveItem" :loading="saving">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 入库对话框 -->
    <el-dialog v-model="stockInDialogVisible" title="入库操作" width="400px">
      <div class="stock-info">
        <p><strong>物品:</strong> {{ selectedItem?.name }}</p>
        <p><strong>当前库存:</strong> {{ selectedItem?.currentStock }} {{ selectedItem?.unit }}</p>
      </div>
      <el-form :model="stockForm" :rules="stockRules" ref="stockFormRef" label-width="100px">
        <el-form-item label="入库数量" prop="quantity">
          <el-input-number v-model="stockForm.quantity" :min="1" controls-position="right" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="stockForm.remark" type="textarea" :rows="3" placeholder="请输入入库备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockInDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStockIn" :loading="saving">确认入库</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 出库对话框 -->
    <el-dialog v-model="stockOutDialogVisible" title="出库操作" width="400px">
      <div class="stock-info">
        <p><strong>物品:</strong> {{ selectedItem?.name }}</p>
        <p><strong>当前库存:</strong> {{ selectedItem?.currentStock }} {{ selectedItem?.unit }}</p>
      </div>
      <el-form :model="stockForm" :rules="stockRules" ref="stockFormRef" label-width="100px">
        <el-form-item label="出库数量" prop="quantity">
          <el-input-number
            v-model="stockForm.quantity"
            :min="1"
            :max="selectedItem?.currentStock || 0"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="stockForm.remark" type="textarea" :rows="3" placeholder="请输入出库备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockOutDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStockOut" :loading="saving">确认出库</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Plus,
  Refresh,
  Box,
  Check,
  Warning,
  Close
} from '@element-plus/icons-vue';
import {
  getInventoryList,
  getInventoryStats,
  getInventoryCategories,
  createInventoryItem,
  updateInventoryItem,
  updateInventoryStock,
  deleteInventoryItem
} from '../../api/inventory';

export default {
  name: 'Inventory',
  components: {
    Plus,
    Refresh,
    Box,
    Check,
    Warning,
    Close
  },
  setup() {
    const loading = ref(false);
    const dialogVisible = ref(false);
    const stockInDialogVisible = ref(false);
    const stockOutDialogVisible = ref(false);
    const isEdit = ref(false);
    const saving = ref(false);
    const itemFormRef = ref();
    const stockFormRef = ref();
    const selectedItem = ref(null);

    // 筛选表单
    const filterForm = reactive({
      category: '',
      status: '',
      keyword: ''
    });

    // 库存数据
    const items = ref([]);
    const inventoryStatsData = ref({
      total: 0,
      normal: 0,
      lowStock: 0,
      outOfStock: 0
    });

    // 物品表单
    const itemForm = reactive({
      id: null,
      name: '',
      sku: '',
      category: '',
      currentStock: 0,
      minStock: 0,
      maxStock: 100,
      unit: '个',
      price: 0
    });

    // 库存操作表单
    const stockForm = reactive({
      quantity: 1,
      remark: ''
    });

    // 表单验证规则
    const itemRules = {
      name: [{ required: true, message: '请输入物品名称', trigger: 'blur' }],
      sku: [{ required: true, message: '请输入SKU编码', trigger: 'blur' }],
      category: [{ required: true, message: '请选择类别', trigger: 'change' }],
      unit: [{ required: true, message: '请输入单位', trigger: 'blur' }]
    };

    const stockRules = {
      quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
      remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
    };

    // 计算属性
    const inventoryStats = computed(() => {
      return {
        total: inventoryStatsData.value.total,
        normal: inventoryStatsData.value.normal,
        low: inventoryStatsData.value.lowStock,
        out: inventoryStatsData.value.outOfStock
      };
    });

    const filteredItems = computed(() => {
      let result = items.value;

      if (filterForm.category) {
        result = result.filter(item => item.category === filterForm.category);
      }

      if (filterForm.status) {
        result = result.filter(item => item.status === filterForm.status);
      }

      if (filterForm.keyword) {
        const keyword = filterForm.keyword.toLowerCase();
        result = result.filter(item => item.name.toLowerCase().includes(keyword));
      }

      return result;
    });

    // 方法
    const loadItems = async () => {
      try {
        loading.value = true;
        const response = await getInventoryList({
          search: filterForm.keyword,
          category: filterForm.category,
          status: filterForm.status
        });

        if (response.success) {
          const inventoryData = response.data.items || response.data.inventory || [];
          items.value = inventoryData.map(item => ({
            id: item.id,
            name: item.name,
            sku: item.sku,
            category: item.category,
            currentStock: item.current_stock,
            minStock: item.min_stock,
            maxStock: item.max_stock,
            unit: item.unit,
            price: parseFloat(item.unit_price || 0),
            status: item.status,
            lastUpdate: item.updated_at
          }));
        } else {
          ElMessage.error(response.message || '获取库存列表失败');
        }
      } catch (error) {
        console.error('获取库存列表失败:', error);
        ElMessage.error('获取库存列表失败');
      } finally {
        loading.value = false;
      }
    };

    const loadStats = async () => {
      try {
        const response = await getInventoryStats();
        if (response.success) {
          const summary = response.data.summary || response.data;
          inventoryStatsData.value = {
            total: summary.total_items || 0,
            normal: summary.active_items || 0,
            lowStock: summary.low_stock_items || 0,
            outOfStock: summary.out_of_stock_items || 0
          };
        } else {
          ElMessage.error(response.message || '获取库存统计失败');
        }
      } catch (error) {
        console.error('获取库存统计失败:', error);
        ElMessage.error('获取库存统计失败');
      }
    };

    const refreshInventory = async () => {
      await loadItems();
      await loadStats();
      ElMessage.success('刷新成功');
    };

    const addItem = () => {
      isEdit.value = false;
      Object.assign(itemForm, {
        id: null,
        name: '',
        sku: '',
        category: '',
        currentStock: 0,
        minStock: 0,
        maxStock: 100,
        unit: '个',
        price: 0
      });
      dialogVisible.value = true;
    };

    const editItem = (item) => {
      isEdit.value = true;
      Object.assign(itemForm, { ...item });
      dialogVisible.value = true;
    };

    const saveItem = async () => {
      try {
        await itemFormRef.value.validate();
        saving.value = true;

        const data = {
          name: itemForm.name,
          sku: itemForm.sku,
          category: itemForm.category,
          current_stock: itemForm.currentStock,
          min_stock: itemForm.minStock,
          max_stock: itemForm.maxStock,
          unit: itemForm.unit,
          unit_price: itemForm.price,
          description: ''
        };

        let response;
        if (isEdit.value) {
          response = await updateInventoryItem(itemForm.id, data);
          ElMessage.success('物品更新成功');
        } else {
          response = await createInventoryItem(data);
          ElMessage.success('物品添加成功');
        }

        if (response.success) {
          dialogVisible.value = false;
          await loadItems();
          await loadStats();
        } else {
          ElMessage.error(response.message || '保存失败');
        }
      } catch (error) {
        console.error('保存失败:', error);
        ElMessage.error('保存失败');
      } finally {
        saving.value = false;
      }
    };

    const deleteItem = async (item) => {
      try {
        await ElMessageBox.confirm(`确认删除物品 "${item.name}" 吗？`, '确认删除', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const response = await deleteInventoryItem(item.id);
        if (response.success) {
          ElMessage.success('物品删除成功');
          await loadItems();
          await loadStats();
        } else {
          ElMessage.error(response.message || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
          ElMessage.error('删除失败');
        }
      }
    };

    const stockIn = (item) => {
      selectedItem.value = item;
      stockForm.quantity = 1;
      stockForm.remark = '';
      stockInDialogVisible.value = true;
    };

    const stockOut = (item) => {
      selectedItem.value = item;
      stockForm.quantity = 1;
      stockForm.remark = '';
      stockOutDialogVisible.value = true;
    };

    const confirmStockIn = async () => {
      try {
        await stockFormRef.value.validate();
        saving.value = true;

        const response = await updateInventoryStock(selectedItem.value.id, {
          quantity: stockForm.quantity,
          operation: 'add'
        });

        if (response.success) {
          ElMessage.success(`成功入库 ${stockForm.quantity} ${selectedItem.value.unit}`);
          stockInDialogVisible.value = false;
          await loadItems();
          await loadStats();
        } else {
          ElMessage.error(response.message || '入库失败');
        }
      } catch (error) {
        console.error('入库失败:', error);
        ElMessage.error('入库失败');
      } finally {
        saving.value = false;
      }
    };

    const confirmStockOut = async () => {
      try {
        await stockFormRef.value.validate();
        saving.value = true;

        const response = await updateInventoryStock(selectedItem.value.id, {
          quantity: stockForm.quantity,
          operation: 'subtract'
        });

        if (response.success) {
          ElMessage.success(`成功出库 ${stockForm.quantity} ${selectedItem.value.unit}`);
          stockOutDialogVisible.value = false;
          await loadItems();
          await loadStats();
        } else {
          ElMessage.error(response.message || '出库失败');
        }
      } catch (error) {
        console.error('出库失败:', error);
        ElMessage.error('出库失败');
      } finally {
        saving.value = false;
      }
    };

    const searchItems = () => {
      // 搜索逻辑已在计算属性中处理
    };

    const resetFilter = () => {
      filterForm.category = '';
      filterForm.status = '';
      filterForm.keyword = '';
    };

    // 辅助方法
    const getItemStatus = (item) => {
      if (item.currentStock <= 0) return 'out';
      if (item.currentStock <= item.minStock) return 'low';
      return 'normal';
    };

    const getCategoryText = (category) => {
      return category || '未知';
    };

    const getCategoryTagType = (category) => {
      const typeMap = {
        '台球用品': 'primary',
        '清洁用品': 'warning',
        '维护用品': 'success'
      };
      return typeMap[category] || 'info';
    };

    const getStatusText = (status) => {
      const statusMap = {
        normal: '库存正常',
        low_stock: '库存不足',
        out_of_stock: '缺货'
      };
      return statusMap[status] || '未知';
    };

    const getStatusTagType = (status) => {
      const typeMap = {
        normal: 'success',
        low_stock: 'warning',
        out_of_stock: 'danger'
      };
      return typeMap[status] || 'info';
    };

    const getStockClass = (item) => {
      if (item.status === 'out_of_stock') return 'stock-out';
      if (item.status === 'low_stock') return 'stock-low';
      return 'stock-normal';
    };

    const formatTime = (timeStr) => {
      if (!timeStr) return '';
      return new Date(timeStr).toLocaleString('zh-CN');
    };

    onMounted(() => {
      loadItems();
      loadStats();
    });

    return {
      loading,
      dialogVisible,
      stockInDialogVisible,
      stockOutDialogVisible,
      isEdit,
      saving,
      itemFormRef,
      stockFormRef,
      selectedItem,
      filterForm,
      items,
      itemForm,
      stockForm,
      itemRules,
      stockRules,
      inventoryStats,
      filteredItems,
      refreshInventory,
      addItem,
      editItem,
      saveItem,
      deleteItem,
      stockIn,
      stockOut,
      confirmStockIn,
      confirmStockOut,
      searchItems,
      resetFilter,
      getCategoryText,
      getCategoryTagType,
      getStatusText,
      getStatusTagType,
      getStockClass,
      formatTime
    };
  }
};
</script>

<style scoped>
.inventory-container {
  padding: 20px;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  color: #2c3e50;
  font-weight: 600;
}

.header-left p {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.normal {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stat-icon.low {
  background: linear-gradient(135deg, #e6a23c, #ebb563);
}

.stat-icon.out {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

/* 筛选卡片 */
.filter-card {
  margin-bottom: 20px;
  border: none;
  border-radius: 12px;
}

/* 表格卡片 */
.table-card {
  border: none;
  border-radius: 12px;
}

/* 库存状态样式 */
.stock-normal {
  color: #67c23a;
  font-weight: bold;
}

.stock-low {
  color: #e6a23c;
  font-weight: bold;
}

.stock-out {
  color: #f56c6c;
  font-weight: bold;
}

/* 库存操作按钮容器 */
.inventory-action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  max-width: 230px;
  overflow-x: auto;
  padding: 2px 0;
}

.inventory-action-buttons::-webkit-scrollbar {
  height: 4px;
}

.inventory-action-buttons::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.inventory-action-buttons::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.inventory-action-buttons::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.inventory-action-buttons .el-button {
  flex-shrink: 0;
  margin: 0;
}

/* 库存信息 */
.stock-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.stock-info p {
  margin: 5px 0;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-row {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .inventory-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: flex-start;
  }

  .stats-row {
    grid-template-columns: 1fr;
  }
}
</style>
